package com.snake.demo.config;

import com.snake.demo.filter.JwtAuthenticationTokenFilter;
import com.snake.demo.service.impl.AccessDeniedHandlerImp;
import com.snake.demo.service.impl.AuthenticationEntryPointImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.annotation.Resource;

/**
 * @Author: snake_skin
 * @Date: 2024/05/18/12:33
 * @Description:
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Resource
    JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;

    @Resource
    AuthenticationEntryPointImpl authenticationEntryPoint;

    @Resource
    AccessDeniedHandlerImp accessDeniedHandlerImp;

    // 设置密码加密规则
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    // 注入用户验证需要的AuthenticationManager
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                // 禁用csrf
                .csrf().disable()
                // 禁用Session
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                // 定义安全规则
                .authorizeRequests()
                // 放行/user/login  anonymous表示匿名,不需要登录即可访问
                .antMatchers("/user/login").anonymous()
                // 除了上面的规则外,所有的请求都需要登录校验 authenticated表示需要登录校验
                .anyRequest().authenticated();
        // 在校验账号密码的过滤器之前 添加token认证过滤器
        http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);

        // 添加异常处理器
        http.exceptionHandling()
                // 认证异常处理器
                .authenticationEntryPoint(authenticationEntryPoint)
                // 授权异常处理器
                .accessDeniedHandler(accessDeniedHandlerImp);
        // 设置spring security允许跨域
        http.cors();
    }
}
